package com.netty.pro.netty.tcp;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;

import java.nio.charset.Charset;
import java.util.UUID;

/**
 * @author xuzn
 * @ClassName: TcpServerHandler
 * @ProjectName netty-pro
 * @date 2020/3/21/9:47
 */
public class TcpServerHandler extends SimpleChannelInboundHandler<ByteBuf> {
  private int count;

  @Override
  public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {

  }

  @Override
  protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
    byte[] content = new byte[msg.readableBytes()];
    // 将数据写入buffer
    ByteBuf buf = msg.readBytes(content);
    // 将内容转成字符串
    String message = new String(content, CharsetUtil.UTF_8);
    System.out.println("服务端接收到的数据:" + message);
    System.out.println("服务端接收到的消息量=" + (this.count++));
    // 服务器端回送消息
    ByteBuf resBuf = Unpooled.copiedBuffer(UUID.randomUUID().toString() + " ", CharsetUtil.UTF_8);
    ctx.writeAndFlush(resBuf);
  }

  @Override
  public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
    ctx.close();
  }
}
